import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

class Image{
    public String name;
    public String url;
}
@WebServlet("/image")
public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //1.扫描/webapp/image路径，看有多少个图片，生成List<Image>
        List<Image> images = loadImage();
        //2.把images给构造到模板页面中
        ServletContext context = this.getServletContext();
        TemplateEngine engine = (TemplateEngine) context.getAttribute("engine");
        WebContext webContext = new WebContext(req,resp,context);
        webContext.setVariable("images",images);
        String html = engine.process("images",webContext);
        resp.getWriter().write(html);
    }
    private List<Image> loadImage(){
        //1.扫描/webapp/image目录
        List<Image> images = new ArrayList<>();
        //2.需要获取到/webapp/image这个目录在磁盘上的绝对路径
        ServletContext context = this.getServletContext();
        //把webapp下面的路径转换成绝对路径
        String path = context.getRealPath("/image");
        System.out.println(path);
        File imageRoot = new File(path);
        File[] files = imageRoot.listFiles();
        for(File f : files){
            Image image = new Image();
            image.name = f.getName();
            image.url = "image/" + f.getName();
            images.add(image);
        }
        return images;
    }
}
